package cn.itcode_02;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @author Aaron
 * @since 2021/3/25 9:48
 * <p>描述：</p>
 */
public class MutexTest {
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(100);

    private static Lock lock = new Mutex();

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }

                lock.lock();
                try {
                    System.out.println(DateTimeFormatter.ofPattern("HH:mm:ss.SSS").format(LocalDateTime.now())
                            + " @ " + Thread.currentThread().getName() + " - " + "获取锁");
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // unlock() 方法调用后，锁会立即被释放，而不是等到 finally 块执行完毕或当前线程结束
                    lock.unlock();
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()
                            + " - " + "释放锁");
                }
            }).start();

        }
    }

}
